const { Reply } = require('../model/reply')
const {Topic} = require('../model/topics')
const {User} = require('../model/user')
const mongoose = require('mongoose')
const { Discussion } = require('../model/discussions')
const {getUserLever} = require("../utils")
const {Level} = require('../model/level')
const config = require('../config')
const moment = require('moment-timezone');

//获取评论列表
exports.getReplyList = async (req, res, next) => {
    try {
        let userVote=[]
        if(req.loginuser){
            const loginuser = await User.findById(req.loginuser._id).select("+likingReplies")
            userVote = loginuser.likingReplies
        }
    
        //分页：获取当前页数
        let page = Math.max(req.query.page - 0, 1) - 1
        //设置每页条数
        const { per_page = 10 } = req.query
        let perpage = Math.max(req.query.per_page * 1, 1)

        let keyword = new RegExp(req.query.keyword)
        const {rootCommentId} = req.query
        let replyList = await Reply.find({
            content: keyword,
            topicId: req.params.id
        })
        .select("+childrenComments")
        .populate({
            path:'replier',
            select:"+experience",
            populate:{
                path:"avatar",
                strictPopulate:false
            }
        })
        .populate('replyTo topicId')
        .populate({
            path:"childrenComments",
            populate: {
                path:"replyTo replier",
                select:"+experience",
                populate:{
                    path:"avatar",
                    strictPopulate:false
                }
            }
        })
        // .limit(perpage)
        // .skip(page * per_page)
        if (!replyList) return res.status(200).json({
            code: 400,
            msg: '获取评论列表失败'
        })
        replyList: await Promise.all(replyList.map( async (item,index,array) => {
            if(item.replier.experience){
                let levelNum= getUserLever(item.replier.experience)
                let {level,url} =await Level.findOne({level:levelNum})
                item.replier._doc["level"] = {
                    level:level,
                    url:url
                }
            } else {
                item.replier._doc["level"] = {
                    level:'unknown',
                    url:`/level/level1.png`
                }
            }
            item.childrenComments = await Promise.all(item.childrenComments.map( async (v,i,arr) => {
                let cReply = await Reply.findById(v).populate({
                    path:"replyTo replier",
                    select:"+experience",
                    populate:{
                        path:"avatar",
                        strictPopulate:false
                    }
                })
                let cDiscuss = await Discussion.findById(v).populate({
                    path:"replyTo replier",
                    select:"+experience",
                    populate:{
                        path:"avatar",
                        strictPopulate:false
                    }
                })

                if(cReply) {
                    if(cReply.replier.experience){
                        let levelNum= getUserLever(cReply.replier.experience)
                        let {level,url} =await Level.findOne({level:levelNum})
                        //返回等级
                        cReply.replier._doc["level"] = {
                            level:level,
                            url:url
                        }
                        cReply.replyTo._doc["level"] = {
                            level:level,
                            url:url
                        }
                    } else {
                        cReply.replier._doc["level"] = {
                            level:'unknown',
                            url:`/level/level1.png`
                        }
                        cReply.replyTo._doc["level"] = {
                            level:'unknown',
                            url:`/level/level1.png`
                        }

                    }
                    if (userVote.includes(cReply._id)){
                        cReply._doc['isVote']=true
                    } else {
                        cReply._doc['isVote']=false
                    }
                    return cReply
                }else if (cDiscuss){
                    if(cDiscuss.replier.experience){
                        let levelNum= getUserLever(cDiscuss.replier.experience)
                        let {level,url} =await Level.findOne({level:levelNum})
                        cDiscuss.replier._doc["level"] = {
                            level:level,
                            url:url
                        }
                        cDiscuss.replyTo._doc["level"] = {
                            level:level,
                            url:url
                        }
                    } else {
                        cDiscuss.replier._doc["level"] = {
                            level:'unknown',
                            url:`/level/level1.png`
                        }

                        cDiscuss.replyTo._doc["level"] = {
                            level:'unknown',
                            url:`/level/level1.png`
                        }

                    }

                    if (userVote.includes(cDiscuss._id)){
                        cDiscuss._doc['isVote']=true
                    } else {
                        cDiscuss._doc['isVote']=false
                    }
                    return cDiscuss
                }else{
                    return "null";
                }
            }));
            if(userVote.includes(item._id)){
                item._doc['isVote']=true
            } else {
                item._doc['isVote']=false
            }
            
            return item
        }))
   
        res.status(200).json({
            code: 200,
            msg: '获取评论列表成功',
            data: replyList
        })
    } catch (err) {
        next(err)
    }
}

//获取指定评论
exports.getReply = async (req, res, next) => {
    try {
        const { fields = "" } = req.query
        //字段过滤
        const selectFields = fields.split(';').filter(f => f).map(f => " +" + f).join("")
        const reply = await Reply.findById(req.params.id).select(selectFields).select("+childrenComments")
        .populate({
            path:"replier childrenComments",
            populate: {
                path:"replier",
                strictPopulate:false
            }
        })

        if (!reply) return res.status(200).json({
            code: 400,
            msg: '获取评论失败，帖子不存在'
        })
        res.status(200).json({
            code: 200,
            msg: '获取评论成功',
            data: reply
        })
    } catch (err) {
        next(err)
    }
}
//新增评论
exports.createReply = async (req, res, next) => {
    try {
        const rootCommentId=req.query.rootCommentId
        let rootComment= await Reply.findById(rootCommentId).select("+childrenComments")
        if(!rootComment) {
            const reply =await new Reply({ ...req.body, replier: req.userData._id,topicId:req.params.id , createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')})
            if(!reply) return res.status(200).json({
                code:400,
                msg:"评论失败"
            })
            await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: +1 } })
            //评论帖子+3
            await User.findByIdAndUpdate(req.userData._id, { $inc: { experience: +3 } })
            let topicUser = await Topic.findById(req.params.id)
            await User.findByIdAndUpdate(topicUser.user, { $inc: { experience: +4 } })
            await reply.save()
            res.status(200).json({
                code: 200,
                msg: '评论成功,经验+3',
                data: reply
            })
        } else {
            const reply =await new Reply({ ...req.body, replier: req.userData._id,topicId:req.params.id,rootCommentId:rootCommentId,replyTo:rootComment.replier })
            await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: +1 } })
            await reply.save()
            rootComment.childrenComments.push(reply._id)
            await rootComment.save()
            if(!reply) return res.status(200).json({
                code:400,
                msg:"评论失败"
            })
            await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: +1 } })
            await reply.save()
            res.status(200).json({
                code: 200,
                msg: '评论成功',
                data: reply
            })
        }
    } catch (err) {
        next(err)
    }
}

//删除评论
exports.deleteReply = async (req, res, next) => {
    try {
        let delComment = await Reply.findById(req.params.id)
        let rootComment = delComment.rootCommentId
        let result = await Reply.findByIdAndUpdate(rootComment, { 
            $pull: { 
                childrenComments: delComment._id
            } ,
        }).select("+childrenComments")

        const data = await Reply.findByIdAndDelete(req.params.id)
        if (!data) return res.status(200).json({
            code: 400,
            msg: '删除评论失败',
        })
        await Topic.findByIdAndUpdate(req.params.id, { $inc: { comments: -1 } })
        res.status(200).json({
            code: 200,
            msg: '删除评论成功',
            data: data
        })
    } catch (err) {
        next(err)
    }
}

//获取用户评论列表
exports.getUserReply = async (req,res,next) => {
    const userId = req.params.id
    const commentList = await Reply.find({replier:userId}).populate("topicId")
    if (!commentList) return res.status(200).json({
        code: 400,
        msg: '获取评论失败',
    })
    res.status(200).json({
        code: 200,
        msg: '获取评论成功',
        data: commentList
    })
}

//点赞评论
exports.likeReply = async (req, res, next) => {
    try {
        let userId = req.userData._id
        const followId = req.params.id
        const user = await User.findById(userId.toString()).select("+likingReplies")
        //如果没有点赞则点赞
        if (!user.likingReplies.map(id => id.toString()).includes(followId)) {
            user.likingReplies.push(followId)
            await user.save()
            const changeComments=await Reply.findByIdAndUpdate(req.params.id, { $inc: { voteCount: +1 } })
            await User.findByIdAndUpdate(changeComments.replier, { $inc: { praiseCount: +1 } })
            res.status(200).json({
                code: 200,
                msg: "点赞成功",
                data: {
                    id: req.params.id
                }
            })
        } else {

            res.status(200).json({
                code: 400,
                msg: "点赞失败",
                data: {
                    id: req.params.id
                }
            })
        }

        // next()
    } catch (err) {
        next(err)
    }
}

//取消点赞评论
exports.unLikeReply = async (req, res, next) => {
    try {
        let userId = req.userData._id
        const user = await User.findById(userId.toString()).select("+likingReplies")
        const index = user.likingReplies.map(id => id.toString()).indexOf(req.params.id)
        if (index > -1) {
            user.likingReplies.splice(index, 1)
            await user.save()
            const changeComments=await Reply.findByIdAndUpdate(req.params.id, { $inc: { voteCount: -1 } })
            await User.findByIdAndUpdate(changeComments.replier, { $inc: { praiseCount: -1 } })
            res.status(200).json({
                code: 200,
                msg: "操作成功",
                data: {
                    id: req.params.id
                }
            })
        } else {
            res.status(200).json({
                code: 400,
                msg: "操作失败",
                data: {
                    id: req.params.id
                }
            })
        }
    } catch (err) {
        next(err)
    }
}